package cn.lili.modules.payment.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.order.order.entity.dto.OrderSearchParams;
import cn.lili.modules.payment.entity.dos.RefundLog;
import cn.lili.modules.payment.mapper.RefundLogMapper;
import cn.lili.modules.payment.service.RefundLogService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 退款日志 业务实现
 *
 * @author Chopper
 * @since 2020-12-19 09:25
 */
@Service
public class RefundLogServiceImpl extends ServiceImpl<RefundLogMapper, RefundLog> implements RefundLogService {

    @Override
    public RefundLog getBySn(String sn) {
        return this.getOne(new LambdaUpdateWrapper<RefundLog>().eq(RefundLog::getAfterSaleNo, sn));
    }


    @Override
    public RefundLog getByOutOrderNo(String outOrderNo) {
        return this.getOne(new LambdaQueryWrapper<RefundLog>().eq(RefundLog::getOutRefundNo, outOrderNo));
    }

    @Override
    public Page<RefundLog> queryRefundLogs(OrderSearchParams searchParams) {
        LambdaQueryWrapper<RefundLog> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(searchParams.getOrderSn())) {
            queryWrapper.like(RefundLog::getOrderSn, searchParams.getOrderSn());
        }
        queryWrapper.orderByDesc(RefundLog::getCreateTime);
        return this.page(PageUtil.initPage(searchParams), queryWrapper);
    }

    @Override
    public void check(String sn) {
        LambdaQueryWrapper<RefundLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RefundLog::getAfterSaleNo, sn);
        RefundLog refundLog = this.getOne(queryWrapper, false);
        //如果退款日志存在 则表明存在问题，抛出异常
        if (refundLog != null) {
            if (Boolean.TRUE.equals(refundLog.getIsRefund())) {
                throw new ServiceException(ResultCode.REFUND_DUPLICATE);
            }
            throw new ServiceException(ResultCode.REFUND_EXCEPTION);
        }
    }
}